<template>
    <div class="article-lists">
        <el-card class="!border-none" shadow="never">
            <el-form ref="formRef" class="mb-[-16px]" :model="queryParams" :inline="true">
                <el-form-item label="银行">
                    <el-input class="w-[280px]" v-model="queryParams.bank_name" clearable />
                </el-form-item>
                <el-form-item label="名称">
                    <el-input class="w-[280px]" v-model="queryParams.name" clearable />
                </el-form-item>
                <el-form-item label="产品ID">
                    <el-input class="w-[280px]" v-model="queryParams.origin_product_id" clearable />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none" shadow="never">
            <div>
                <el-button type="primary" class="mb-4" @click="onOpen">
                    <span>对接人配置</span>
                </el-button>
            </div>
            <el-table size="large" v-loading="pager.loading" :data="pager.lists">
                <el-table-column label="序号" type="index" :index="indexAdd" min-width="90" fixed />
                <el-table-column label="产品ID" min-width="100" prop="id" />
                <el-table-column label="第三方ID" min-width="100" prop="origin_product_id" />
                <el-table-column label="产品分类" prop="origin_product_cate_name" min-width="160">
                    <template #default="{ row }">
                        <span>{{ row.origin_product_cate_name.replace(/,/g, '') }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="贷款类型" prop="loan_type_name" min-width="160" />
                <el-table-column label="银行" prop="bank_name" min-width="160" />
                <el-table-column label="产品名称" prop="name" min-width="160" />
                <el-table-column label="产品logo" min-width="160">
                    <template #default="{ row }">
                        <image-contain v-if="row.logo" :src="row.logo" :width="60" :height="45"
                            :preview-src-list="[row.logo]" preview-teleported fit="contain" />
                    </template>
                </el-table-column>
                <el-table-column label="补贴方式" prop="subsidy" min-width="180" >
					<template #default="{ row }">
                        <span v-if="row.subsidy.id == 0">-</span>
						<span v-if="row.subsidy.subsidy_type == 1">补贴金额</span>
						<span v-if="row.subsidy.subsidy_type == 2">根据贷款额度返点</span>
					</template>
				</el-table-column>
				<el-table-column label="补贴金额" prop="subsidy" min-width="180" >
					<template #default="{ row }">
                        <span v-if="row.subsidy.id == 0">-</span>
						<span v-else-if="row.subsidy.subsidy_type == 1">{{ row.subsidy.money }}</span>
						<span v-else-if="row.subsidy.subsidy_type == 2">{{ row.subsidy.num }}%</span>
					</template>
				</el-table-column>
                <el-table-column label="最高额度（万）" prop="quota" min-width="160" >
                    <template #default="{ row }">{{row.quota/10000}}</template>
                </el-table-column>
                <el-table-column label="授信期限" prop="credit_month" min-width="160">
                    <template #default="{ row }">
                        <el-tag v-for="(item, index) in row.credit_month" :key="index" type="info"
                            size="small">{{ item == 1 ? '1个月' : item == 2 ? '2个月' : item == 3 ? '3个月' : item == 6 ? '6个月' :item == 9 ? '9个月' : item == 12 ? '1年' : item == 18 ? '1年6个月': item == 24 ? '2年' : item == 36 ? '3年' : item == 48 ? '4年' : item == 60 ? '5年' : item == 120 ? '10年' : item == 240 ? '20年' : item == 360 ? '30年' : '' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="利率类型" prop="rate_type" min-width="160">
                    <template #default="{ row }"> {{ row.rate_type == 1 ? '年化利率' : '日化利率' }} </template>
                </el-table-column>
                <el-table-column label="利率值" min-width="160">
                    <template #default="{ row }">
                        {{ row.rate_type == 1 ? ((parseInt(String(row.rate_start * 10000)) / 100).toString() + '%') :
                            ((parseInt(String(row.rate_start * 1000000)) / 1000).toString() + '‰') }}
                        -
                        {{ row.rate_type == 1 ? (parseInt(String(row.rate_end * 10000)) / 100).toString() + '%' :
                            (parseInt(String(row.rate_end * 1000000)) /1000).toString() + '‰' }}
                    </template>
                </el-table-column>
                <el-table-column label="还款方式" prop="repayment_type" min-width="160">
                    <template #default="{ row }"> {{ localGetRepaymentTypeText(row.repayment_type) }} </template>
                </el-table-column>
                <el-table-column label="状态" prop="is_enable" min-width="160">
                    <template #default="{ row }">
                        <span v-if="row.is_enable == 0" style="color:red"> 已下架 </span>
                        <span v-if="row.is_enable == 1"> 已上架 </span>
                    </template>
                </el-table-column>
                <el-table-column label="来自" prop="source" min-width="160">
                    <template #default="{ row }">
                        <span v-if="row.source == 1">小麒乖乖</span>
                        <span v-if="row.source == 2">蓝鲸纪</span>
                    </template>
                </el-table-column>
                <el-table-column label="app显示状态" prop="is_enable" min-width="160">
                    <template #default="{ row }">
                        <span v-if="row.is_enable == 0" style="color:red">隐藏</span>
                        <span v-if="row.is_enable == 1">显示</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button v-if="row.is_enable == 0" v-perms="['product.online_product/updateStatus']"
                            type="primary" link @click="handleUpdateStatus(row.id, 1)">显示</el-button>
                        <el-button v-if="row.is_enable == 1" v-perms="['product.online_product/updateStatus']"
                            type="danger" link @click="handleUpdateStatus(row.id, 0)">隐藏</el-button>
                        <el-button v-perms="['onlineProduct/detail']" type="primary" link >
                            <router-link :to="{ path: getRoutePath('onlineProduct/detail'), query: { id: row.id } }">详情</router-link>
                        </el-button>
                       <el-button v-perms="['product.product/saveSubsidy']"
                            type="warning" link @click="setSubsidy(row)">设置补贴</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        
        <popup
            ref="popupRef"
            title="对接人配置"
            width="500px"
            confirm-button-text="确认"
            @confirm="handleConfirm"
            :async="true"
        >
            <div>
                <el-form ref="formConfig" class="mb-[-16px]" :model="configParams" :rules="rules" label-width="180px">
                    <el-form-item label="聊天id(渠道聊天的IM号)" prop="id">
                        <!-- <el-select class="w-[280px]" v-model="configParams.id" filterable clearable>
                                <el-option v-for="(item) in person_list" :label="item.name" :value="item.id" :key="item.id" />
                            </el-select> -->
                            <el-input class="w-[280px]" v-model="configParams.id" clearable />
                    </el-form-item>
                    <el-form-item label="对外显示名称" prop="real_name">
                        <el-input class="w-[280px]" v-model="configParams.real_name" clearable />
                    </el-form-item>
                    <el-form-item label="对外显示职务" prop="position">
                        <el-input class="w-[280px]" v-model="configParams.position" clearable />
                    </el-form-item>
                </el-form>
            </div>
        </popup>

        <el-dialog v-model="subsidyVisible" title="补贴设置" width="500">
			<div class="mb-2">参与后，渠道与客户以该产品达成合作后，用户会获得平台补贴</div>
			<el-form :model="form" :rules="show_rules" ref="formShow" label-width="120">
				<el-form-item label="补贴方式" prop="subsidy_type">
					<el-radio-group v-model="form.subsidy_type">
						<el-radio :label="1">直接补贴</el-radio>
						<el-radio :label="2">根据贷款金额返点（%）</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item v-if="form.subsidy_type == 1" label="补贴金额（元）" label-width="120px" prop="money">
					<el-input-number
						v-model="form.money"
						class="w-[300px]"
						controls-position="right"
					/>
				</el-form-item>
				<el-form-item v-if="form.subsidy_type == 2" label="补贴金额（%）" label-width="120px" prop="num">
					<el-input-number
						v-model="form.num"
						class="w-[300px]"
						controls-position="right"
					/>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
				<el-button @click="subsidyVisible = false">取消</el-button>
				<el-button type="primary" v-perms="['product.product/saveSubsidy']" @click="showAdd">
					确定
				</el-button>
				</div>
			</template>
		</el-dialog>

    </div>
</template>
<script lang="ts" setup name="onlineProductLists">
import { onlineProductLists, onlineProductStatus, contactPersonList, getContactPerson, setContactPerson } from '@/api/product/online'
import { saveSubsidy } from '@/api/operation';
import { usePaging } from '@/hooks/usePaging';
import feedback from '@/utils/feedback';
import { isEmpty } from "@/utils/util";
import Popup from '@/components/popup/index.vue'
import type { FormInstance } from 'element-plus';
import {getRoutePath} from '@/router';

const queryParams = reactive({
    bank_name: '',
    name: '',
    origin_product_id: '',
})
const setSubsidy = (row:any) => {
    form.online_product_id = row.id;
    if (row.subsidy.id != 0) {
        form.id = row.subsidy.id;
        form.subsidy_type = row.subsidy.subsidy_type;
        if (row.subsidy.subsidy_type == 1) {
            form.money = row.subsidy.money;
        } else {
            form.num = row.subsidy.num;
        }
    } else {
        form.subsidy_type = '';
        form.money = undefined;
        form.num = undefined;
        form.id = undefined;
    }
    subsidyVisible.value = true;
}
const subsidyVisible = ref(false)
const formShow = shallowRef<FormInstance>()
// 弹窗提交的表单
const form:any = reactive({
    id: undefined,
    online_product_id: undefined,
    subsidy_type: '',
    money: undefined,
    num: undefined
})
const show_rules = reactive({
    subsidy_type: [{required: true, message: '请选择补贴方式', trigger: 'blur'}],
    money: [{required: true, message: '请填写补贴金额', trigger: 'blur'}],
    num: [{required: true, message: '请填写补贴金额', trigger: 'blur'}],
})
// 表单确认
const showAdd = async () => {
    await formShow.value?.validate();
    console.log(form)
    // return false;
    await saveSubsidy(form)
    subsidyVisible.value = false;
    getLists()
}

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: onlineProductLists,
    params: queryParams
})
const indexAdd = (index: number) => {
    const page = pager.page // 当前页码
    const pagesize = pager.size // 每页条数
    return index + 1 + (page - 1) * pagesize
}

const localGetRepaymentTypeText = (repaymentTypes: number[] | null): string => {
    //1.先息后本 2.等额本息 3.等额本金 4.一次性还本付息 5.随借随还
    let repaymentTypeStr = ''
    if (!isEmpty(repaymentTypes)) {
        (repaymentTypes as number[]).forEach((item, index) => {
            if (item == 1) {
                repaymentTypeStr += '先息后本/'
            } else if (item == 2) {
                repaymentTypeStr += '等额本息/'
            } else if (item == 3) {
                repaymentTypeStr += '等额本金/'
            } else if (item == 4) {
                repaymentTypeStr += '一次性还本付息/'
            } else if (item == 5) {
                repaymentTypeStr += '随借随还/'
            }

        })
    }
    return repaymentTypeStr.slice(0, -1)
}


const localGetAccessAreasText = (accessAreaArr: Array<any>): string => {
    let accessAreaText = ''
    accessAreaArr.forEach((item, index) => {
        accessAreaText += (item?.Name) + '/'
    })
    return accessAreaText.replace(/[\\//]$/, "");
}

const handleUpdateStatus = async (id: number, num: number) => {
    try {
        if (num == 0) {
            await feedback.confirm('隐藏之后，用户将不能看到该产品，是否确认隐藏？？', '下架')
        } else {
            await feedback.confirm('显示之后，用户可看到该产品，是否确认显示？', '上架')
        }
        await onlineProductStatus({
            id,
            is_enable: num
        })
        getLists()
    } catch (error) {
        console.log(error)
    }

}


const popupRef = shallowRef<InstanceType<typeof Popup>>()
const onOpen = () => {
    popupRef.value?.open()
}
// 获取对接人列表
const person_list:any = ref([])
const getPerson = async () => {
    const res = await contactPersonList({})
    console.log(res)
    person_list.value = res
}
getPerson()
const configParams:any = reactive({
    id: '',
    // user_str: '',
    real_name: '',
    position: ''
})
const formConfig = shallowRef<FormInstance>()
// 表单校验 确认提交
const handleConfirm = async () => {
    await formConfig.value?.validate()
    console.log(configParams)
    await setContactPerson({
        user_str: configParams.id,
        real_name: configParams.real_name,
        position: configParams.position
    })
    popupRef.value?.close()
}
const rules = reactive({
    id: [{ required: true, message: '请选择对接人', trigger: 'blur' }],
    real_name: [{ required: true, message: '请填写对外显示名称', trigger: 'blur' }],
    position: [{ required: true, message: '请填写对外显示职务', trigger: 'blur' }],
})

// 获取对接人的配置
const getPersonInfo = async () => {
    const data = await getContactPerson()
    console.log(data)
    Object.keys(configParams).forEach((key)=>{
        configParams[key] = data[key]
    })
    configParams.id = Number(data.user_str);
}
getPersonInfo()

onActivated(() => {
    getLists()
})

getLists()
</script>